function _CreateInputBar(containerIdForAdd, inputbarId, inputId, buttonId, labelText, portionValue, buttonText){
 var randomID = inputbarId;
 var div = $("<div>");
 div.attr("class", "portionInput");
 div.attr("id", randomID);

 $(containerIdForAdd).append(div);
 
 var label = $("<label>");
 label.html(labelText + ": ");
 label.attr("for", "#" + inputId);
 
 $("#"+randomID).append(label);
 
 var input = $("<input>");
 input.attr("id", inputId);
 input.attr("type", "text");
 input.attr("size", "1");
 input.attr("onKeyPress", "return numbersonly(this, event)");
 input.attr("MAXLENGTH", "2");
 input.attr("value", portionValue);
 
 $("#"+randomID).append(input);
 $('#'+inputId).css('text-align','right');
 
 var button = $("<button>");
 button.attr("id", buttonId);
 button.html(buttonText);
 
 $("#"+randomID).append(button);
}


function _CreateTable(parentContainerID, newTableId, headerData, bodyData){
 var table = $("<table>");
 table.attr("id", newTableId);
 table.attr("class", "calculator");
 $(parentContainerID).append(table);
 
 _CreateTableHeader(table, headerData);
 _CreateTableBody(table, bodyData);
}

function _CreatePriceSentense(parentContainerID, newPriceId, inputId, tableId, columnId){
 var sentense = $("<p>");
 sentense.attr("id", newPriceId);
 sentense.attr("class", "priceSentense");
 $(parentContainerID).append(sentense);
 
 var price = CalculateTotalAmount(tableId, columnId).toFixed(2);
 if(isNaN(price)){
 	price = "unbekannt";
 }
 
 $("#"+newPriceId).html("Der Gesammtpreis der Zutataten f&uuml;r <span class='portionenInSentense'>" + $(inputId).val() + 
 "</span> Portion/en betr&auml;gt ca. <span class='price'>" + price + "</span>" + " &#8364;. Die Preise sind zeitlich und/oder regional bedingt und nur ein grober Richtwert.");
 
}

function RefreshPriceSentense(priceId, inputId, tableId, columnId){
 var price = CalculateTotalAmount(tableId, columnId).toFixed(2);
  if(isNaN(price)){
 	price = "unbekannt";
 }
 $(priceId).html("Der Gesammtpreis der Zutataten f&uuml;r <span class='portionenInSentense'>" + $(inputId).val() + "</span> Portion/en betr&auml;gt ca. <span class='price'>" + price + "</span>" + " &#8364;. Die Preise sind zeitlich und/oder regional bedingt und nur ein grober Richtwert.");
}


function _CreateTableHeader(table, data){
  if (table == null || table.length < 1) return;
  var html = "<thead><tr>";
  jQuery.each(data, function(index, value){
  html += "<th>" + value + "</th" + "<br></br>";
  });
  html += "</tr></thead>";
  table.prepend(html);
};

function _CreateTableBody(table, data){
  if (table == null || table.length < 1) return;
  jQuery.each(data, function(index, value){
  var trow = $("<tr>");
   jQuery.each(value, function(indexInner, valueInner){
   $("<td>")
   .text(valueInner)
   .appendTo(trow);
   });
   trow.appendTo(table)
  });
}

function CreateCalcControl(parentContainerId, inputbarId, inputId, buttonId, labelText, portionValue, buttonText, newTableId, headerData, bodyData, priceId, columnId, priceSentenseId){
	_CreateInputBar(parentContainerId,inputbarId, inputId, buttonId, labelText, portionValue, buttonText);
	_CreateTable(parentContainerId, newTableId, headerData, bodyData);
	_CreatePriceSentense(parentContainerId, priceSentenseId, '#'+inputId, '#'+newTableId, columnId);
	ResizeDivs('#'+inputbarId, '#'+newTableId, '#'+priceSentenseId);
}

function CalculateStuff(event, tableId, columnId, oldPortion, newPortion, IsRound){
 $(tableId+'>tbody>tr>td:nth-child(' +columnId +')').each( function(){
 	if($(this).text().indexOf("," > 0)){
 		$(this).text($(this).text().replace(',','.'));
 	}

  var intCellValue = parseFloat($(this).text());
  var intOldPortion = parseFloat(oldPortion);
  var intNewPortion =  parseFloat(newPortion);
  var result = parseFloat(intCellValue / intOldPortion * intNewPortion);
  
  var reformedString = result.toFixed(2);
  if(isNaN(reformedString)){
 	reformedString = "?";
  }
  else{
  	reformedString.toString().replace('.',',');
  }
  
  $(this).text(reformedString);
 });
};

function OnCalculate(event, tableID, oldValue, newValue, inputID, priceSentenseID, inputID, inputbarID){
	CalculateStuff(event, "#"+tableID, 1, oldValue, newValue);
  	CalculateStuff(event, "#"+tableID, 4, oldValue, newValue);  
 	RefreshPriceSentense('#'+priceSentenseID, '#'+inputID, '#'+tableID, 4);
  	CheckIfRightUnitAndChangeWhenPossible('#'+tableID, 1, 2);
  	ResizeDivs('#'+inputbarID, '#'+tableID, '#'+priceSentenseID);
  
}

function CheckIfRightUnitAndChangeWhenPossible(tableId, columnIdPortion, columnIdUnit){
	var portionArray = [];
 	var unitArray= [];
 	$(tableId+'>tbody>tr>td:nth-child(' +columnIdPortion +')').each( function(){
 		portionArray.push($(this).text())
 	});
 	
 	$(tableId+'>tbody>tr>td:nth-child(' +columnIdUnit +')').each( function(){
 		unitArray.push($(this).text())
 	}); 	
 	for(var i=0,j=portionArray.length; i<j; i++){
 		var formatedPortionsValue;
 		var floatFormatedPortionsValue;
 		if(portionArray[i].toString().indexOf(",")>0){
 			formatedPortionsValue = portionArray[i].toString().replace(',','.');
 		}
 		else{
 			formatedPortionsValue = portionArray[i];
 		}
 		var floatFormatedPortionsValue = parseFloat(formatedPortionsValue);
 		
 		 if(floatFormatedPortionsValue>=1000){
 			 if (unitArray[i] === "g") {
 				 unitArray[i] = "kg";
 				 portionArray[i] = parseFloat(formatedPortionsValue / 1000).toFixed( 2 );

 			 };	
 			 if (unitArray[i] === "ml") {
 			 	 unitArray[i] = "l";
 				 portionArray[i] = parseFloat(formatedPortionsValue / 1000).toFixed( 2 );

 			 };	
 		 }
 		 if(floatFormatedPortionsValue<=1){
 			  if (unitArray[i] === "kg") {
 				 unitArray[i] = "g";
 				 portionArray[i] = parseFloat(formatedPortionsValue * 1000).toFixed( 2 );
 			 };	
 			 
 			 if (unitArray[i] === "l") {
 			 	 unitArray[i] = "ml";
 				 portionArray[i] = parseFloat(formatedPortionsValue * 1000).toFixed( 2 );

 			 };	
 		 }
  		 if(floatFormatedPortionsValue>=9){
 			  if (unitArray[i] === "TL") {
 				 unitArray[i] = "EL";
 				 portionArray[i] = parseFloat(formatedPortionsValue / 3).toFixed( 2 );

 			 };	
 		 }
  		 if(floatFormatedPortionsValue<=3){
 			  if (unitArray[i] === "EL") {
 				 unitArray[i] = "TL";
 				 portionArray[i] = parseFloat(formatedPortionsValue * 3).toFixed( 2 );
 			 };	
 		 } 		 		 
 	 };
  	
 	 var counter = 0; 	
 	 $(tableId+'>tbody>tr>td:nth-child(' +columnIdPortion +')').each( function(){
  	 	$(this).text(portionArray[counter].toString().replace('.',','));
  		counter += 1;
  		 
 	 });
  	
 	 var counter = 0; 	
 	 $(tableId+'>tbody>tr>td:nth-child(' +columnIdUnit +')').each( function(){
  		$(this).text(unitArray[counter]);
  		counter += 1;
 	 });
 	 
};


function AddLinkToColumnValues(tableId, columnId, linkList){
 var counter = 0;
 $(tableId+'>tbody>tr>td:nth-child(' +columnId +')').each( function(){
  var newAttr = $("<a>");
  newAttr.attr("href",linkList[counter]);
  newAttr.html($(this).text());
  $(this).text("");
  $(this).append(newAttr);
  counter+=1;
 });
};

function ResizeDivs(inputbarID, tableID, priceSentenseID){
	var tableWith = $(tableID).width()
	$(inputbarID).width(tableWith)
	$(priceSentenseID).width(tableWith)
	
	
}

function SetNewNumberByInput(inputID){
  var newValue = $(inputID).val();
  if(newValue > 99){
    $(inputID).val(99);
   newValue = $(inputID).val();
  }
  if(newValue < 1){
    $(inputID).val(1);
   newValue = $(inputID).val();
  }
  
  return newValue;
};

function CalculateTotalAmount(tableId, columnId){
 var result = 0;
 $(tableId+'>tbody>tr>td:nth-child(' +columnId +')').each( function(){
  result += parseFloat($(this).text().toString().replace(',','.'));
 });
 return result;
};

function numbersonly(myfield, e, dec)
//
// copyright 1999 Idocs, Inc. http://www.idocs.com
// Distribute this script freely but keep this notice in place
//
{
	
	var key;
	var keychar;

	if (window.event)
   		key = window.event.keyCode;
	else if (e)
   		key = e.which;
	else{
   		return true;
   	}
	keychar = String.fromCharCode(key);

	// control keys
	if ((key==null) || (key==0) || (key==8) || 
    	(key==9) || (key==13) || (key==27) ){
    		
   		return true;
   	}

	// numbers
	else if ((("0123456789").indexOf(keychar) > -1)){
		return true;
	}

	// decimal point jump
	else if (dec && (keychar == "."))
   	{
   		myfield.form.elements[dec].focus();
   		return false;
   	}
	else
   		return false;
}